package com.jhws.business.car.controller;

import com.alibaba.fastjson.JSON;
import com.jhws.common.base.bo.JsonRespData;
import com.jhws.business.car.bo.*;
import com.jhws.business.car.service.CarInfoService;
import com.jhws.business.car.service.DiscountService;
import com.jhws.business.car.service.ParkingLotService;
import com.jhws.common.pay.bo.Order;
import com.jhws.common.pay.service.OrderService;
import com.jhws.common.pay.service.WXPayService;
import com.jhws.core.exception.BizException;
import com.jhws.util.DateUtil;
import com.jhws.util.GetId;
import com.jhws.util.QRCodeUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/car/carInfo")
public class CarInfoController {
    @Resource
    private CarInfoService carInfoService;
    @Resource
    private ParkingLotService parkingLotService;
    @Resource
    private WXPayService wxPayService;
    @Resource
    private DiscountService discountService;
    @Resource
    private OrderService orderService;

    /**
     * 查询车辆信息
     *
     * @param param
     * @return
     */
    @RequestMapping("queryCarInfoList.x")
    @ResponseBody
    public Map<String, Object> queryCarInfoList(@RequestParam Map param) {
        return carInfoService.queryCarInfoList(param);
    }

    /**
     * 根据业主和停车场获取对应的车辆信息
     */
    @RequestMapping("getCarInfoList.x")
    @ResponseBody
    public JsonRespData getCarInfoList(String parkId, String ownerCode) {
        List<CarInfo> carInfos = carInfoService.queryCarInfoByWhere(" where park_id ='" + parkId + "' and owner_code = '" + ownerCode + "'");
        return new JsonRespData("", 1, carInfos);
    }

    @RequestMapping("getMonthlyCardOrder.x")
    @ResponseBody
    public JsonRespData getMonthlyCardOrder(String commCode, String ownerCode, String parkId, String plateNumber, int months) {
        ParkingLot parkingLot = parkingLotService.queryParkingLotInfo(parkId);
        if (parkingLot == null)
            return new JsonRespData("", -1, "停车场不存在！");
        if (StringUtils.isEmpty(plateNumber))
            return new JsonRespData("", -1, "车牌号码不能为空！");
        if (months == 0)
            return new JsonRespData("", -1, "充值月数必须大于0！");

        List<CarInfo> carInfos = carInfoService.queryCarInfoByWhere(" where park_id ='" + parkId + "' and plate_number = '" + plateNumber + "'");
        CarInfo carInfo = carInfos != null && carInfos.size() > 0 ? carInfos.get(0) : null;

        Date date = new Date(); //当前时间
        String expirationTime; //未充值前到期时间
        String renewExpirationTime; //充值后到期时间
        if (carInfo != null) {
            expirationTime = DateUtil.parseDateFormat(carInfo.geteEndTime(), DateUtil.DATE_FORMAT);
            renewExpirationTime = DateUtil.getDateByMonth(carInfo.geteEndTime(), months, DateUtil.DATE_FORMAT);
        } else {
            expirationTime = DateUtil.parseDateFormat(date, DateUtil.DATE_FORMAT);
            renewExpirationTime = DateUtil.getDateByMonth(date, months, DateUtil.DATE_FORMAT);
        }
        float totalFee = parkingLot.getMonthlyRate() * months;
        float actualTotalFee = totalFee;
        /*计算优惠策略*/
        String where = "where start_month=(select max(startMonth) from Discount where park_id='" + parkId + "' and start_month <= '" + months + "') and park_id='" + parkId + "'";
        List<Discount> discounts = discountService.queryDiscounts(where);
        Discount discount = discounts != null && discounts.size() > 0 ? discounts.get(0) : null;
        if (discount != null) {
            if (CarConstant.DISCOUNT_DIS.equals(discount.getDiscountType()) && discount.getDiscount() > 0) {
                actualTotalFee = totalFee * discount.getDiscount();
            } else {
                if (CarConstant.DISCOUNT_GIVE.equals(discount.getDiscountType()) && discount.getDiscount() > 0) {
                    renewExpirationTime = DateUtil.getDateByDay(DateUtil.stringDate(renewExpirationTime, DateUtil.DATE_FORMAT), (int) (discount.getDiscount() * 30), DateUtil.DATE_FORMAT);
                }
            }
        }

        String totalFeeTest = "0.01";
        /* 生成临时订单基本信息 */
        Order order = new Order();
        order.setId(Long.valueOf(GetId.randomID()));
        order.setAttach(plateNumber);
        order.setAttach2(parkId);
        order.setOrderType(CarOrderPayModule.ORDER_CAR_MONTH);
        order.setTime(date);
        order.setCommCode(commCode);
        order.setBody("车辆月卡缴费");

        Map<String, Object> map = new HashMap<>();
        map.put("plateNumber", plateNumber);
        map.put("parkId", parkId);
        map.put("months", months);
        map.put("expirationTime", expirationTime);
        map.put("renewExpirationTime", renewExpirationTime);
        map.put("totalFee", totalFee);
        map.put("actualTotalFee", actualTotalFee);

        order.setDetail(JSON.toJSONString(map));
        order.setOwnerCode(ownerCode);
        totalFeeTest = wxPayService.genTotalFee(totalFeeTest);
        order.setTotalFee(String.valueOf(Double.valueOf(totalFeeTest) / 100));
        orderService.save(order);
        return new JsonRespData("", 1, order);
    }

    /**
     * 获取月卡缴费二维码
     */
    @RequestMapping("qrcode.x")
    public void createQRCode(HttpServletResponse response, HttpServletRequest request, String parkId, String orderId) throws Exception {
        ParkingLot parkingLot = parkingLotService.queryParkingLotInfo(parkId);
        if (parkingLot == null || parkingLot.getPayCustomerId() == 0) {
            throw new BizException("-1", "", "停车场参数错误！");
        }
        String domainName = request.getScheme() + "://" + request.getServerName();
        //禁止缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Content-Disposition", "attachment;fileName=qrcode.jpg");
        String webUrl = "/api/v2/car/anon/monthQrcode?orderId=" + orderId + "&" + "appId=" + wxPayService.getAppId(parkingLot.getPayCustomerId());

        String url = domainName + webUrl;
        ImageIO.write(QRCodeUtil.createImage(url, null, true), "JPEG", response.getOutputStream());
        response.getOutputStream().flush();
    }
}
